<?php
session_start();
if(!isset($_SESSION['admin'])){
    header("location: login.php");
    exit;
}
require_once 'PmsDb.php';
class Order {
	private static $API_KEY = '7d63c6157ae94e59a4d886f31b0f5cad4b5ef8c62c4048e586b53930d44bb836';
	public static function liuliang($jsonArr) {
		// $url = "https://capi.fdn-test.chinanetcenter.com/user/order";
		$url = "https://capi.fdn.chinanetcenter.com/user/order";
		$json = json_encode ( $jsonArr );
		$source = $json . self::$API_KEY;
		$digest = md5 ( $source );
		$result = self::httpPost2CpCenter ( $url, $json, $digest );
		return $result;
	}
	public static function httpPost2CpCenter($url, $json, $digest) {
		$header = array (
				"X-FDN-Auth:$digest",
				"Content-Type: application/json; charset=utf-8",
				"X-AjaxPro-Method:ShowList" 
		);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
		// curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $json );
		$response = curl_exec ( $ch );
		$errno = curl_errno ( $ch );
		if ($errno > 0) {
			throw new \Exception ( curl_error ( $ch ), $errno );
		}
		return $response;
	}
}
function addOrder($phone, $cpOrderNos, $transNo, $orderId) {
	try {
		global $pmsDb;
		$sql = "insert into t_fdn_order(phone,cp_order_no,trans_no,order_id,updated_at) values(?,?,?,?,?)";
		$result = $pmsDb->pdo->prepare ( $sql );
		$result->bindValue ( 1, $phone );
		$result->bindValue ( 2, $cpOrderNos );
		$result->bindValue ( 3, $transNo );
		$result->bindValue ( 4, $orderId );
		$result->bindValue ( 5, date("Y-m-d H:i:s") );
		$result->execute ();
	} catch ( PDOException $e ) {
		return false;
	}
	return true;
}

$phone = $_POST ['phone'];
$cpOrderNos = $_POST['cp_order'];

$jsonArr = array ();
$jsonArr ["phone"] = $phone;
$jsonArr ["cpOrderNos"] = $cpOrderNos;
$jsonArr ["cpUserName"] = "yuxsh";
$jsonArr ["timestamp"] = date ( "YmdHis" );
$jsonArr ["transNo"] = "fdn" . date ( "YmdHis" ) . rand ( 1000, 9999 );
$re = Order::liuliang ( $jsonArr );
$jsonObj = json_decode ( $re, true );
$code = $jsonObj ['responseCode'];
header ( "Content-type: application/json" );
if ($code == 10000) {
	$orderId = $jsonObj ['responseData'] ['orderId'];
	$pmsDb = new PmsDb ( 'fdn' );
	$re = addOrder ( $phone, $jsonArr ["cpOrderNos"], $jsonArr ["transNo"], $orderId );
	if ($re) {
		echo json_encode ( array (
				"code" => 0 
		) );
		die ();
	}
}

echo json_encode ( array (
		"code" => - 1 
) );
die ();

?>
